using Colorful.CMS.Core;
using Colorful.Database;
using Colorful.Image;
using Colorful.Models;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace Colorful.CMS.Controllers
{
    public class HomeController : BaseController
    {
        private const string TOKEN = "6eb0eef28f394964bd40f6afa39c1e70";

        #region Apps首页
        [Route("/")]
        public IActionResult Index(string uid, string token)
        {
            if (WebService.IsDevelopment)
            {
                uid = "5a557e3f63d92439c0b70486";
            }
            if (string.IsNullOrEmpty(uid))
            {
                return Redirect($"http://www.7chd.cn/api/wx/openid?url={$"{HttpContext.Request.GetDomainUrl()}/".UrlEncode()}&scope=userinfo");
            }
            using (var wxDb = WeiXin.DbHelper.GetDb())
            {
                var wxUser = wxDb.WeChatUsers.FirstOrDefault(a => a.Id == uid);
                string tokenStr = null;
                if (!WebService.IsDevelopment)
                    tokenStr = SecurityHelper.GetSignature(wxUser.Id, "wxuser", wxUser.SessionId, wxUser.LoginTicks.ToString());
                if (WebService.IsDevelopment || token == tokenStr)
                {
                    using (var db = Apps.DbHelper.GetDb())
                    {
                        var member = db.Members.FirstOrDefault(a => a.WeChatUserId == uid);
                        if (member == null)
                        {
                            member = new Apps.Models.Member()
                            {
                                LoginId = string.IsNullOrEmpty(wxUser.OpenId) ? wxUser.UnionId : wxUser.OpenId,
                                ByOrder = db.Members.GetId(),
                                WeChatUserId = uid,
                                Apps = new List<int>(),
                                Status = AuditingStatus.Waiting
                            };
                            member.NumberId = 10000 + member.ByOrder;
                        }
                        member.Nickname = wxUser.NickName;
                        member.Photo = wxUser.HeadImgUrl;
                        member.LastLogin = DateTime.Now;
                        member.LastModify = DateTime.Now;
                        member.SessionId = db.GetUniqueId();
                        member.Sex = wxUser.Sex;
                        db.Members.Save(member);

                        var permissions = member.Apps.Select(a => (long)a).ToList();
                        permissions.Insert(0, (long)MyPermission.Member);
                        this.Login(new AppUser()
                        {
                            Id = member.Id,
                            LoginId = member.LoginId,
                            Name = member.Name,
                            Sex = member.Sex,
                            Photo = member.Photo,
                            Nickname = member.Nickname,
                            Flag = "Apps",
                            LastLogin = DateTime.Now,
                            Mobile = member.Mobile,
                            Email = member.Email,
                            NumberId = member.NumberId,
                            Permissions = permissions,
                            SessionId = member.SessionId
                        });
                    }
                    //return this.GetTextResult($"<img src='{wxUser.HeadImgUrl}' /><h3>{wxUser.NickName}</h3>");
                }
            }
            return View();
        }
        #endregion

        #region 注册CMS
        [EnableCors("*")]
        [Route("/cms/reg")]
        public IActionResult Register(string token, string appKey, string domain, string appSecret)
        {
            if (token != TOKEN || string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(domain))
                return this.GetResult(false, "参数错误！");
            var domains = domain.Split(',');
            if (domains.Length > 3)
                return this.GetResult(false, "最多绑定三个域名！");
            using (var db = DbHelper.GetDb())
            {
                var member = db.Members.FirstOrDefault(a => a.AppKey == appKey);
                if (member == null)
                {
                    member = new Member()
                    {
                        AppKey = appKey,
                        AppSecret = CommonHelper.GetRandomAllStr(32),
                        NumberId = db.Members.GetId(),
                        Domains = domains.ToList(),
                        Status = AuditingStatus.Success
                    };
                    member.ByOrder = member.NumberId;
                }
                else if (appSecret == member.AppSecret)
                {
                    member.Domains = domains.ToList();
                }
                db.Members.Save(member);
                return this.GetResult(true, member.AppSecret);
            }
        }
        #endregion

        #region 测试
        [Route("test112311a")]
        public IActionResult Test(string act)
        {
            try
            {
                using (var db = CMSDbHelper.GetDb())
                {
                    switch (act)
                    {
                        case "updatemenu":
                            {
                                db.Menus.UpdateMany(a => a.Id > 0, db.Menus.GetUpdate().Rename("Sort", "Type"));
                            }
                            break;
                        case "error":
                            throw new InvalidException("错误测试！");
                    }
                }
                return this.GetTextResult("Succ!");
            }
            catch (Exception ex)
            {
                return this.GetResult(ex);
            }
        }
        #endregion

        //public FileContentResult Captcha()
        //{
        //    string code = "";
        //    var ms = CommonHelper.CreateCodeImg(out code);
        //    HttpContext.Session.SetString("LoginValidateCode", code);
        //    Response.Body.Dispose();
        //    return File(ms.ToArray(), @"image/png");
        //}
    }
}
